package main

import (
	"context"
	"log"

	"github.com/bytedance/sonic"
	"github.com/hibiken/asynq"
)

type emailPayload struct {
	UserID int
}

func main() {
	srv := asynq.NewServer(
		asynq.RedisClusterClientOpt{
			Addrs: []string{
				"192.168.0.138:6379",
				"192.168.0.143:6379",
				"192.168.0.140:6379",
				"192.168.0.142:6379",
				"192.168.0.141:6379",
				"192.168.0.139:6379",
			},
		},
		asynq.Config{
			Concurrency: 10,
			Queues: map[string]int{
				"high":    10,
				"default": 5,
				"low":     1,
			},
		},
	)

	// 写法1
	if err := srv.Run(asynq.HandlerFunc(handler)); err != nil {
		log.Fatal(err)
	}
}

func handler(ctx context.Context, task *asynq.Task) error {
	switch task.Type() {
	case "email:welcome":
		var p emailPayload
		if err := sonic.Unmarshal(task.Payload(), &p); err != nil {
			log.Printf("could not unmarshal payload: %v", err)
			return err
		}
		log.Printf("sending welcome email to user %d", p.UserID)
	case "email:reminder":
		var p emailPayload
		if err := sonic.Unmarshal(task.Payload(), &p); err != nil {
			log.Printf("could not unmarshal payload: %v", err)
			return err
		}
		log.Printf("sending email reminder to user %d", p.UserID)
	default:
		log.Printf("unexpected task type: %s", task.Type())
	}

	return nil
}
